<template>
  <div class="p-2">
    <el-card shadow="hover" class="mb-2">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="内容类型" prop="modelType">
          <el-select v-model="queryParams.modelType" placeholder="请选择内容类型" clearable>
            <el-option v-for="item in modelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="queryParams.fieldName" placeholder="请输入字段名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="字段标识" prop="fieldKey">
          <el-input v-model="queryParams.fieldKey" placeholder="请输入字段标识" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="字段类型" prop="fieldType">
          <el-select v-model="queryParams.fieldType" placeholder="请选择字段类型" clearable>
            <el-option v-for="(label, value) in fieldTypeOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cms:modelField:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['cms:modelField:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['cms:modelField:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="fieldList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="字段名称" align="center" prop="fieldName" />
        <el-table-column label="字段标识" align="center" prop="fieldKey" />
        <el-table-column label="字段类型" align="center" prop="fieldType">
          <template #default="scope">
            {{ fieldTypeOptions[scope.row.fieldType as keyof typeof fieldTypeOptions] || scope.row.fieldType }}
          </template>
        </el-table-column>
        <el-table-column label="应用模型" align="center" prop="modelType">
          <template #default="scope">
            {{ modelTypeOptions.find((item) => item.value === scope.row.modelType)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="是否必填" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.required === 1 ? 'danger' : 'info'">
              {{ scope.row.required === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序号" align="center" prop="sort" width="80" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
              v-hasPermi="['cms:modelField:edit']"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cms:modelField:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cms:modelField:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改字段配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="modelFieldFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用模型" prop="modelType">
          <el-select v-model="form.modelType" placeholder="请选择应用模型" :disabled="form.id !== undefined" class="w-[100%]">
            <el-option v-for="item in modelTypeOptions" :key="item.value" :label="item.label" :value="item.value">
              <span>{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="form.fieldName" placeholder="请输入字段名称" />
        </el-form-item>
        <el-form-item label="字段标识" prop="fieldKey">
          <el-input v-model="form.fieldKey" placeholder="请输入字段标识" :disabled="form.id !== undefined" />
          <el-text class="text-sm text-gray-500">字段标识只能包含字母、数字和下划线，且必须以字母开头</el-text>
        </el-form-item>
        <el-form-item label="字段类型" prop="fieldType">
          <el-select v-model="form.fieldType" placeholder="请选择字段类型" :disabled="form.id !== undefined">
            <el-option v-for="(label, value) in fieldTypeOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认值" prop="defaultValue">
          <el-input v-model="form.defaultValue" placeholder="请输入默认值" />
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-radio-group v-model="form.required">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="form.sort" :min="0" controls-position="right" class="w-[100%]" />
        </el-form-item>
        <el-form-item label="输入提示" prop="placeholder">
          <el-input v-model="form.placeholder" placeholder="请输入输入提示" />
        </el-form-item>
        <el-form-item label="验证规则" prop="validateRule">
          <el-input v-model="form.validateRule" type="textarea" placeholder="请输入验证规则，JSON格式" :rows="4" />
          <el-text class="text-sm text-gray-500">格式：[{"type": "email", "message": "请输入正确的邮箱地址"}]</el-text>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ModelField">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, nextTick, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { listModelField, getModelField, delModelField, addModelField, updateModelField } from '@/api/cms/modelField';
import { ModelFieldVO, ModelFieldForm, ModelFieldQuery } from '@/api/cms/modelField/types';
import { FieldType, ModelType } from '@/api/cms/model/types';
import { listModel } from '@/api/cms/model'; // 导入内容模型列表接口

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 定义表单引用
const queryFormRef = ref<FormInstance>();
const modelFieldFormRef = ref<FormInstance>();

// 字段类型选项映射
const fieldTypeOptions = {
  text: '文本框',
  textarea: '文本域',
  editor: '富文本编辑器',
  number: '数字',
  image: '图片',
  gallery: '图片集',
  file: '文件',
  video: '视频',
  select: '下拉选择',
  radio: '单选框',
  checkbox: '复选框',
  datetime: '日期时间',
  switch: '开关',
  json: 'JSON对象'
} as const;

// 模型类型选项 - 改为响应式数据
const modelTypeOptions = ref<Array<{ label: string; value: string }>>([]);

// 获取内容模型列表
const getModelOptions = async () => {
  try {
    const res = await listModel({ state: '0' }); // 只获取启用的模型
    if (res.code === 200 && res.rows) {
      modelTypeOptions.value = res.rows.map((model) => ({
        label: model.modelName,
        value: model.modelType
      }));
    }
  } catch (error) {
    console.error('获取内容模型失败:', error);
    proxy?.$modal.msgError('获取内容模型失败');
  }
};

// 列表数据
const fieldList = ref<ModelFieldVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const buttonLoading = ref(false);

// 表单参数
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ModelFieldForm = {
  id: undefined,
  fieldName: '',
  fieldKey: '',
  fieldType: '',
  defaultValue: '',
  options: '',
  required: 0,
  modelType: '',
  sort: 0,
  placeholder: '',
  validateRule: '',
  status: '0',
  remark: ''
};

const data = reactive<PageData<ModelFieldForm, ModelFieldQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelType: undefined,
    fieldName: undefined,
    fieldKey: undefined,
    fieldType: undefined
  },
  rules: {
    modelType: [{ required: true, message: '请选择应用模型', trigger: 'change' }],
    fieldName: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
    fieldKey: [
      { required: true, message: '请输入字段标识', trigger: 'blur' },
      { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '字段标识只能包含字母、数字和下划线，且必须以字母开头', trigger: 'blur' }
    ],
    fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
    placeholder: [{ required: true, message: '请输入输入提示', trigger: 'blur' }]
  }
});

// 使用 computed 来监听表单数据变化
const formData = computed(() => data.form);

const { queryParams, form, rules } = toRefs(data);

/** 查询字段列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listModelField(queryParams.value);
    fieldList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  // 创建新的对象而不是引用
  const newForm = { ...initFormData };
  // 确保所有字段都有初始值
  Object.keys(newForm).forEach((key) => {
    if (newForm[key] === undefined) {
      if (typeof initFormData[key] === 'string') {
        newForm[key] = '';
      } else if (typeof initFormData[key] === 'number') {
        newForm[key] = 0;
      }
    }
  });

  form.value = newForm;
  nextTick(() => {
    modelFieldFormRef.value?.resetFields();
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  (queryFormRef.value as FormInstance)?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ModelFieldVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加字段';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ModelFieldVO) => {
  // 先打开对话框，再重置表单
  dialog.visible = true;
  dialog.title = '修改字段';

  // 延迟执行重置和数据赋值
  nextTick(async () => {
    reset();
    const _id = row?.id || ids.value[0];
    try {
      const res = await getModelField(_id);

      if (res.code === 200 && res.data) {
        const fieldData = {
          id: res.data.id,
          fieldName: res.data.fieldName || '',
          fieldKey: res.data.fieldKey || '',
          fieldType: res.data.fieldType || '',
          defaultValue: res.data.defaultValue || '',
          options: res.data.options || '',
          required: res.data.required || 0,
          modelType: res.data.modelType || '',
          sort: res.data.sort || 0,
          placeholder: res.data.placeholder || '',
          validateRule: res.data.validateRule || '',
          status: res.data.status || '0',
          remark: res.data.remark || ''
        };

        form.value = fieldData;

        // 手动更新表单的每个字段
        Object.keys(fieldData).forEach((key) => {
          form.value[key] = fieldData[key];
        });
      } else {
        proxy?.$modal.msgError(res.msg || '获取字段详情失败');
      }
    } catch (error) {
      proxy?.$modal.msgError('获取字段详情失败');
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  (modelFieldFormRef.value as FormInstance)?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateModelField(form.value);
        } else {
          await addModelField(form.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ModelFieldVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除字段编号为"' + _ids + '"的数据项？');
  loading.value = true;
  try {
    await delModelField(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  } finally {
    loading.value = false;
  }
};

/** 状态修改 */
const handleStatusChange = async (row: ModelFieldVO) => {
  const text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.fieldName + '"字段吗？');
    await updateModelField(row);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};

// 在组件挂载时获取模型列表
onMounted(async () => {
  await getModelOptions(); // 先获取模型列表
  await getList(); // 再获取字段列表
});
</script>
